package cn.edu.tsinghua.weibo.servlet;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONArray;
import cn.edu.tsinghua.weibo.entity.User;
import cn.edu.tsinghua.weibo.util.ContentFilter;
import cn.edu.tsinghua.weibo.util.DB;
import cn.edu.tsinghua.weibo.util.FormateDate;

@SuppressWarnings("serial")
public class Comment extends HttpServlet {

	private static final String SQL_DELETE = "DELETE FROM comment WHERE id=?";
	private static final String SQL_INSERT = "INSERT INTO comment(content, time, userid, weiboid) VALUES(?, ?, ?, ?)";
	private static final String SQL_QUERY = "SELECT u.id userid, u.avatar, u.nick, c.id commentid, c.content, c.time, u2.id weibouserid, w.id weiboid" +
											" FROM comment c, user u, user u2, weibo w" +
											" WHERE u.id=c.userid AND c.weiboid=w.id AND w.userid=u2.id AND c.weiboid=?" +
											" ORDER BY time DESC";
	
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		int weiboid = Integer.parseInt(request.getParameter("weiboid"));
		HttpSession session = request.getSession();
		int userid = ((User) session.getAttribute("user")).getId();
		String action = request.getParameter("action");
		
		try {
			
			Connection connection = DB.getConnection();
			PreparedStatement preparedStatement = null;
			ResultSet resultSet = null;
			
			if(action.equals("insert")) {
				String content = request.getParameter("content");
				preparedStatement = connection.prepareStatement(SQL_INSERT);
				preparedStatement.setString(1, content);
				preparedStatement.setTimestamp(2, new Timestamp(System.currentTimeMillis()));
				preparedStatement.setInt(3, userid);
				preparedStatement.setInt(4, weiboid);
				preparedStatement.executeUpdate();
			}
			
			if(action.equals("delete")) {
				int commentid = Integer.parseInt(request.getParameter("commentid"));
				preparedStatement = connection.prepareStatement(SQL_DELETE);
				preparedStatement.setInt(1, commentid);
				preparedStatement.executeUpdate();
			}
			
			if(!action.equals("delete")) {
				preparedStatement = connection.prepareStatement(SQL_QUERY);
				preparedStatement.setInt(1, weiboid);
				resultSet = preparedStatement.executeQuery();
				
				ArrayList<Map<String, Object>> arrayList = new ArrayList<Map<String, Object>>();
				while(resultSet.next()) {
					Map<String, Object> map = new HashMap<String, Object>();//Hashtable
					map.put("sessionuserid", userid);
					map.put("weibouserid", resultSet.getInt("weibouserid"));
					map.put("weiboid", resultSet.getInt("weiboid"));
					map.put("userid", resultSet.getInt("userid"));
					map.put("avatar", resultSet.getString("avatar"));
					map.put("nick", resultSet.getString("nick"));
					map.put("commentid", resultSet.getInt("commentid"));
					map.put("content", ContentFilter.getFiltratedContent(resultSet.getString("content")));
					map.put("time", FormateDate.getFormattedDate(resultSet.getTimestamp("time").getTime()));
					arrayList.add(map);
				}
				
				JSONArray jsonArray = JSONArray.fromObject(arrayList);
				response.setContentType("text/html; charset=utf-8");  
				response.getWriter().print(jsonArray);
			}
			DB.close(resultSet, preparedStatement, connection);
			
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
}
